package com.google.mr.okhttptest.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/11/27.
 */

public  abstract class BaseFragment extends Fragment {

    public Context mContext;
    private Unbinder unbinder;
    private boolean isViewCreated=false;
    private boolean isUserUIvisible=false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getContentViewLayoutID()!=0){
            return inflater.inflate(getContentViewLayoutID(),container,false);
        }else{
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    public abstract int getContentViewLayoutID();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        initView();
        //如果加载数据的方法放在这里,那么ViewPager加载左右两侧界面的时候
        // 用户在看不到界面的情况下会损耗流量数据进行加载看不到的网络请求
        //因此我们需要在用户滑动到当前界面的情况下再开始加载数据
        //initData();
        isViewCreated=true;//onViewCreated方法执行
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            isUserUIvisible=true;
            lazyLoad();
        }else {
            isUserUIvisible=false;
        }
    }

    /**
     * 数据懒加载的判断
     */
    private void lazyLoad() {
        if (isViewCreated&&isUserUIvisible){
            initData();
            isViewCreated=false;
            isUserUIvisible=false;
        }
    }

    /**
     * 界面初始化
     */
    protected abstract void initView();

    /**
     * 界面数据懒加载
     */
    protected abstract void initData();


    /**
     * Fragment继承问题 在android不同版本之间会有Fragment Context与Activity不同的问题,需要我们统一处理
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isUserUIvisible=false;
        isViewCreated=false;
        unbinder.unbind();
    }
}
